package com.bdqn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import sun.plugin.dom.core.Node;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Sjlx2xg {
    public static void main(String[] args) {
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document document=db.parse("ch02/Practical/手机收藏信息.xml");
            NodeList nodeList=document.getElementsByTagName("Brand");
            for (int i=0;i<nodeList.getLength();i++){
                if (nodeList.item(i).getNodeType()== Node.ELEMENT_NODE){
                    Element element=(Element)nodeList.item(i);
                    String name=element.getAttribute("name");
                    if (name.equals("三星")){
                        element.setAttribute("name","SAMSUNG");
                    }
                }
            }
            TransformerFactory factory=TransformerFactory.newInstance();
            Transformer transformer=factory.newTransformer();
            DOMSource domSource=new DOMSource(document);

            //设置字符编码
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            StreamResult result= new StreamResult(new FileOutputStream("ch02/Practical/手机收藏信息.xml"));
            transformer.transform(domSource,result);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

    }
}
